package com.training.hatton.dropboxclient;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;
import com.training.hatton.dropboxclient.utill.DropboxService;

public class DropboxLoginActivity extends Activity {

	private static final AccessType ACCESS_TYPE = AccessType.DROPBOX;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dropbox_login);
		AndroidAuthSession session = buildSession();
		DropboxService.setDBApi( new DropboxAPI<AndroidAuthSession>(session)); 
		DropboxService.getDBApi().getSession().startAuthentication(DropboxLoginActivity.this);
	}

	@Override
	public void onResume() {
		super.onResume();  
		if (DropboxService.getDBApi().getSession().authenticationSuccessful()) {
			Toast.makeText(this, "SuccesAuth", Toast.LENGTH_SHORT).show();
			try {
				DropboxService.getDBApi().getSession().finishAuthentication();
				AccessTokenPair tokens = DropboxService.getDBApi().getSession().getAccessTokenPair();
				storeKeys(tokens.key, tokens.secret);
				startActivity(new Intent(this, DropboxLauncherActivity.class));
				finish();
			} catch (IllegalStateException e) {
				Log.d("DbAuthLog", "Error authenticating", e);
			}
		}
	}
	
	private String[] getKeys() {
		SharedPreferences prefs = getSharedPreferences(
				DropboxService.DROPBOX_PREFS_NAME, 0);
		String key = prefs.getString(DropboxService.ACCESS_KEY_NAME, null);
		String secret = prefs
				.getString(DropboxService.ACCESS_SECRET_NAME, null);
		if (key != null && secret != null) {
			String[] ret = new String[2];
			ret[0] = key;
			ret[1] = secret;
			return ret;
		} else {
			return null;
		}
	}

	private void storeKeys(String key, String secret) {
		DropboxService.setKeys(key, secret);
		SharedPreferences prefs = getSharedPreferences(
				DropboxService.DROPBOX_PREFS_NAME, 0);
		Editor edit = prefs.edit();
		edit.putString(DropboxService.ACCESS_KEY_NAME, key);
		edit.putString(DropboxService.ACCESS_SECRET_NAME, secret);
		edit.commit();
	}

	private AndroidAuthSession buildSession() {
		AppKeyPair appKeyPair = new AppKeyPair(DropboxService.APP_KEY,
				DropboxService.APP_SECRET);
		AndroidAuthSession session;

		String[] stored = getKeys();
		if (stored != null) {
			AccessTokenPair accessToken = new AccessTokenPair(stored[0],
					stored[1]);
			session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE,
					accessToken);
		} else {
			session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
		}

		return session;
	}

}
